package com.xu.fountain.Controller;

import com.xu.fountain.Entity.AdminInfoEntity;
import com.xu.fountain.Entity.UserEntity;
import com.xu.fountain.Repository.AdminInfoRepository;
import com.xu.fountain.Repository.UserRepository;
import com.xu.fountain.Util.CodeUtil;
import com.xu.fountain.Util.MD5Util;
import com.xu.fountain.Util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.apache.log4j.Logger;

/**
 * @Message: created by XUBO on 2018/5/1
 * @Description:
 */
@RestController
public class PublicController {

    Logger LOG = Logger.getLogger(PublicController.class);
    @Autowired
    private UserRepository userRepos;
    @Autowired
    private AdminInfoRepository AdminRepos;


    @RequestMapping("/user/login")
    @ResponseBody
    public Result test(@RequestParam String username, @RequestParam String password){
        LOG.info( "用户名："+username );
        UserEntity user1 = userRepos.findByUsername( username ) ;
        LOG.info( "用户："+user1 );
        if (user1 == null) {
            return new Result(404,"用户名不存在",user1);
        }
        if ((MD5Util.encode(password)).equals( user1.getPassword() )){
            user1.setToken(CodeUtil.getCode(20) );
            userRepos.save( user1 );
            return new Result(1,"登陆成功",user1);
        }
        return new Result(0,"用户名密码不正确",null);
    }

    @RequestMapping(value="/user/register")
    public UserEntity saveUser(UserEntity user){
        user.setPassword(MD5Util.encode(user.getPassword()));
        user.setToken(CodeUtil.getCode(20));
        return userRepos.save(user);
    }



    @RequestMapping("/admin/login")
    @ResponseBody
    public Result login(@RequestParam String username, @RequestParam String password){
        LOG.info( "用户名："+username );
        AdminInfoEntity user1 = AdminRepos.findByUser( username ) ;
        LOG.info( "用户："+user1 );
        if (user1 == null) {
            return new Result(404,"用户名不存在",user1);
        }
        if ((MD5Util.encode(password)).equals( user1.getPwd() )){
            user1.setToken(CodeUtil.getCode(20) );
            AdminRepos.save( user1 );
            return new Result(1,"登陆成功",user1);
        }
        return new Result(0,"用户名密码不正确",null);
    }

}
